package com.metrology.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Common {
	private static final String CHARSET = "UTF-8";
	private static final String randChars = "0123456789abcdefghigklmnopqrstuvtxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
	private static Random random = new Random();

	public static int THUMB_WIDTH_300 = 300;
	public static int THUMB_HEIGHT_200 = 200;
	public static int THUMB_WIDTH_100 = 100;
	public static int THUMB_HEIGHT_100 = 100;


	public static String BACK_APPLICATION = "BACK_APPLICATION";
	public static String BACK_REFUSAL = "BACK_REFUSAL";
	public static String BACK_AGREE = "BACK_AGREE";
	public static String BACK_PAY = "BACK_PAY";
	public static String BACK_TO_INFO = "BACK_TO_INFO";
	public static String BACK_TO_INFO_AGREE = "BACK_TO_INFO_AGREE";
	public static String BACK_TO_INFO_REFUSAL = "BACK_TO_INFO_REFUSAL";
	


	// 年月日时分秒对应的毫秒数(月是按30天)
	public static final long second = 1000;
	public static final long minute = second * 60;
	public static final long hour = minute * 60;
	public static final long day = hour * 24;
	public static final long month = day * 30;
	public static final long year = month * 12;
	
	
	/**
	 * 禁止实例化
	 */
	private Common(){
		
	}

	/**
	 * 对象是否为空 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean empty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && obj.equals("")) {
			return true;
		} else if (obj instanceof Number && ((Number) obj).doubleValue() == 0) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		return false;
	}

	/**
	 * author Bruce Zhang
	 * 
	 * @param str
	 * @return 如果字符串不为null也不为空字符串返回true
	 */
	public static boolean notEmptyStr(String str) {
		if (str != null && !"".equals(str) && !"null".equals(str)) {
			return true;
		}
		return false;
	}

	public static boolean notNull(String str) {
		if (str != null) {
			return true;
		}
		return false;
	}

	public static boolean emptyStr(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

	public static String trim(String text) {
		if (text == null) {
			return "";
		}
		return text.trim();
	}

	public static String urlEncode(String s) {
		return urlEncode(s, CHARSET);
	}

	/**
	 * 用指定的编码转换字符串
	 * @param s
	 * @param enc
	 * @return
	 */
	public static String urlEncode(String s, String enc) {
		if (!empty(s)) {
			try {
				return URLEncoder.encode(s, enc);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return s;
	}

	public static String urlDecode(String s) {
		return urlDecode(s, CHARSET);
	}

	public static String urlDecode(String s, String enc) {
		if (!empty(s)) {
			try {
				return URLDecoder.decode(s, enc);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return s;
	}

	public static String md5(String arg0) {
		return Md5Util.encode(arg0);
	}

	public static String getRandStr(int length, boolean isOnlyNum) {
		int size = isOnlyNum ? 10 : 62;
		StringBuffer hash = new StringBuffer(length);
		for (int i = 0; i < length; i++) {
			hash.append(randChars.charAt(random.nextInt(size)));
		}
		return hash.toString();
	}

	/**
	 * 字符串类型转换成日期类型
	 * @param dateStr 日期字符串
	 * @param format 日期字符串格式?
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDate(String dateStr, String format)
			throws ParseException {
		if (empty(dateStr))
			return null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.parse(dateStr);
	}
	

	/**
	 * 得到0和max之间的随机数
	 * @param max
	 * @return
	 */
	public static int rand(int max) {
		return rand(0, max);
	}

	/**
	 * 得到min和max之间的随机数
	 * @param min
	 * @param max
	 * @return
	 */
	public static int rand(int min, int max) {
		if (min < max) {
			return random.nextInt(max - min + 1) + min;
		} else {
			return min;
		}
	}

	/**
	 * 通过data得到yyyyMMdd格式的字符串
	 * @param date
	 * @return
	 */
	public static String getFormatDate(Date date) {
		return getFormatDate(date, "yyyyMMdd");
	}

	/**
	 * 通过data得到format格式的字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String getFormatDate(Date date, String format) {
		DateFormat f = new SimpleDateFormat(format);
		return f.format(date);
	}

	
	/**
	 * 通过date得到星期几
	 * @param date
	 * @return
	 */
	public static String getWeekDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int weekday = cal.get(Calendar.DAY_OF_WEEK);
		String weekDayFormat = "";
		switch (weekday) {
		case 1:
			weekDayFormat = "星期日";
			break;
		case 2:
			weekDayFormat = "星期一";
			break;
		case 3:
			weekDayFormat = "星期二";
			break;
		case 4:
			weekDayFormat = "星期三";
			break;
		case 5:
			weekDayFormat = "星期四";
			break;
		case 6:
			weekDayFormat = "星期五";
			break;
		case 7:
			weekDayFormat = "星期六";
			break;
		}

		return weekDayFormat;
	}

	public static String htmlSpecialChars(String string) {
		return htmlSpecialChars(string, 1);
	}

	public static String htmlSpecialChars(String text, int quotestyle) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
			case '&':
				sb.append("&amp;");
				break;
			case '<':
				sb.append("&lt;");
				break;
			case '>':
				sb.append("&gt;");
				break;
			case '"':
				if (quotestyle == 1 || quotestyle == 2) {
					sb.append("&quot;");
				} else {
					sb.append(character);
				}
				break;
			case '\'':
				if (quotestyle == 2) {
					sb.append("&#039;");
				} else {
					sb.append(character);
				}
				break;
			default:
				sb.append(character);
				break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}

	/**
	 * 字符串的回车转成网页的换行
	 * @param text
	 * @return
	 */
	public static String nl2br(String text) {
		if (text == null || text.length() == 0) {
			return text;
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
			case '\r':
				sb.append("<br/>");
				sb.append(character);
				character = iterator.next();
				if (character == '\n') {
					character = iterator.next();
				}
				break;
			case '\n':
				sb.append("<br/>");
				sb.append(character);
				character = iterator.next();
				if (character == '\r') {
					sb.append(character);
					character = iterator.next();
				}
				break;
			default:
				sb.append(character);
				character = iterator.next();
				break;
			}
		}
		return sb.toString();
	}

	/**
	 * 字符串截断加fix,如...
	 * @param str
	 * @param length
	 * @param fix
	 * @return
	 */
	public static String cutStr(String str, int length, String fix) {
		if (empty(str))
			return str;
		if (length > str.length())
			return str;
		return str.substring(0, length) + fix;
	}

	/**
	 * 在day的基础上加上x天数
	 * @param day
	 * @param x
	 * @return
	 */
	public static String addDate(String day, int x) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = format.parse(day);
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		if (date == null)
			return "";
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, x);
		date = cal.getTime();
		cal = null;
		return format.format(date);
	}

	/**
	 * 在date的基础上加上x天数
	 * @param date
	 * @param x
	 * @return
	 */
	public static Date addDate(Date date, int x) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, x);
		date = cal.getTime();
		cal = null;
		return date;
	}

	/**
	 * 在date的基础上加上x分钟数
	 * @param date
	 * @param minutes
	 * @return
	 */
	public static Date addMinutes(Date date, int minutes) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, minutes);
		return date = cal.getTime();
	}
	/**
	 * 在date的基础上加上x小时数
	 * @param date
	 * @param minutes
	 * @return
	 */
	public static Date addHours(Date date, int hours) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.HOUR_OF_DAY, hours);
		return date = cal.getTime();
	}

	/**
	 * author Bruce Zhang
	 * 
	 * @param dateStr
	 *            时间字符串
	 * @return 时间过滤显示函数,如10分钟前
	 */
	public static String getDate(Object dateStr) {
		try {
			SimpleDateFormat format2 = new SimpleDateFormat("MM月dd日 HH:mm");
			SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date date = new Date();
			if (dateStr == null) {
				return "";
			} else {
				if (dateStr instanceof String) {
					if ("".equals(dateStr)) {
						return "";
					} else {
						date = format3.parse(dateStr.toString());
					}
				} else if (dateStr instanceof Date) {
					date = (Date) dateStr;
				} else {
					return "";
				}
				int nowYear = Calendar.getInstance().get(Calendar.YEAR);
				int year = Integer.parseInt(format3.format(date)
						.substring(0, 4));
				long chaDate = new Date().getTime() - date.getTime();
				if (chaDate / (1000 * 60) < 1) {
					return "1分钟前";
				} else if (chaDate / (1000 * 60) < 60) {
					return chaDate / (1000 * 60) + "分钟前";
				} else if (chaDate / (1000 * 60 * 60) < 24) {
					return chaDate / (1000 * 60 * 60) + "个小时前";
				} else if (year < nowYear) {
					return format3.format(date);
				} else if (chaDate / (1000 * 60 * 60 * 24) < 3) {
					return chaDate / (1000 * 60 * 60 * 24) + "天前";
				} else {
					return format2.format(date);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * author Bruce Zhang
	 * 
	 * @param pattern
	 *            日期格式：如"年"，"月"
	 * @param target
	 *            距离当前几天或几个小时
	 * @return 具体时间
	 */
	public static String getTargetTime(String pattern, Integer target) {
		long t = 0;
		if ("年".equals(pattern)) {
			t = year;
		} else if ("月".equals(pattern)) {
			t = month;
		} else if ("日".equals(pattern)) {
			t = day;
		} else if ("时".equals(pattern)) {
			t = hour;
		} else if ("分".equals(pattern)) {
			t = minute;
		} else if ("秒".equals(pattern)) {
			t = second;
		}
		t = new Date().getTime() - t * target;
		DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return f.format(new Date(t));
	}

	public static void deleteImage(String webAppPath, String imageFile){
		String fileName = webAppPath + File.separator + imageFile;
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}
	}

	public static int strlen(String text) {
		return strlen(text, CHARSET);
	}

	public static int strlen(String text, String charsetName) {
		if (text == null || text.length() == 0) {
			return 0;
		}
		int length = 0;
		try {
			length = text.getBytes(charsetName).length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return length;
	}

	/**
	 * 字符串是否是email
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		return Common.strlen(email) > 6
				&& email.matches("^[\\w\\-\\.]+@[\\w\\-\\.]+(\\.\\w+)+$");
	}

	public static String stripSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length());
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
			case '\'':
				sb.append("'");
				break;
			case '"':
				sb.append('"');
				break;
			case '\\':
				sb.append(iterator.next());
				break;
			default:
				sb.append(character);
				break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}

	public static String addSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
			case '\'':
			case '"':
			case '\\':
				sb.append("\\");
			default:
				sb.append(character);
				break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}

	/**
	 * 得到文件的扩展名
	 * @param filePath
	 * @return
	 */
	public static String fileext(String filePath) {
		int sl = filePath.length();
		if (sl < 2) {
			return "";
		}
		int lastPoint = filePath.lastIndexOf(".");
		if (lastPoint < 0) {
			return "";
		}
		return filePath.substring(lastPoint + 1, filePath.length());
	}

	

	
	public static String getDomain(String url) {
		if (empty(url))
			return null;
		try {
			Pattern p = Pattern.compile(
					"^(http|ftp)://.*.(com|cn|net|org|biz|info|cc|tv)",
					Pattern.CASE_INSENSITIVE);
			Matcher matcher = p.matcher(url);
			matcher.find();
			return matcher.group();
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * author Bruce Zhang
	 * 
	 * @param pageCount
	 *            >=0的整数
	 * @return 0~pageCount的整数
	 */
	public static Integer getRandom(int pageCount) {
		if (pageCount <= 0) {
			return 1;
		}
		Random random1 = new Random();
		return random1.nextInt(pageCount) + 1;
	}

	public static boolean randomSuccess(int effect) {
		Random random = new Random();
		int number = random.nextInt(100);
		if (number <= effect)
			return true;
		return false;
	}

	// 判断是传入内容否含有图片
	public static List<String> getContainedImg(String str) {
		List<String> list = new ArrayList<String>();
		Pattern p = Pattern
				.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
		Matcher m = p.matcher(str);
		if (m.find()) {
			list.add(m.group(1));
		}
		return list;
	}

	public static String parseListToString(List<String> doorplateList) {
		StringBuffer doorplate = new StringBuffer("");
		if (doorplateList == null || doorplateList.size() == 0) {
			doorplate.append("('')");
		} else {
			for (int i = 0; i < doorplateList.size(); i++) {
				if (i == 0) {
					doorplate.append("('" + doorplateList.get(i) + "'");
				} else {
					doorplate.append(",'" + doorplateList.get(i) + "'");
				}
				if (i == doorplateList.size() - 1) {
					doorplate.append(")");
				}
			}
		}
		return doorplate.toString();
	}

	/**
	 * 将网页文件地址转换成字节数组
	 * @param picUrl
	 * @return
	 */
	public static byte[] picUrlToByte(String picUrl) {
		URL urlObj;
		byte[] b = null;
		try {
			urlObj = new URL(picUrl);
			URLConnection connection = urlObj.openConnection();
			InputStream is = connection.getInputStream();
			b = inputStreamToByte(is);
		} catch (MalformedURLException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			// e.printStackTrace();
		}

		return b;
	}

	/**
	 * inputstream 转字节数组
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] inputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte imgdata[] = bytestream.toByteArray();
		bytestream.close();
		return imgdata;
	}

	
	// URL编码
	public static String URLEncode(String str) {
		if (emptyStr(str))
			return "";
		try {
			return java.net.URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	// URL解码
	public static String URLDecode(String str) {
		if (emptyStr(str))
			return "";
		try {
			return java.net.URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	// 获取文本url
	public static Boolean checkUrl(String content) {
		String reg = ".*[(http|ftp|file|www)]://.*";
		Pattern p =Pattern .compile(reg);
		Matcher m = p.matcher(content);
		if(m.matches()){
			return true;
		}else{
			return false;
		}
	}
	
	public static int getNowMonth(){
		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH);
		return month+1;
	}
	
	public static int getNextMonth(){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		int month = cal.get(Calendar.MONTH);
		return month+1;
	}
	
	/**
	 * 比较两个日期之间相差的天数
	 * @author grieous
	 * @param fDate
	 * @param oDate
	 * @return
	 */
	public static int daysOfTwo(Date fDate, Date oDate) {
	       Calendar aCalendar = Calendar.getInstance();
	       aCalendar.setTime(fDate);
	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       aCalendar.setTime(oDate);
	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       return day2-day1;
	    }
	
	/**  
     * @author grieous
     * 基本功能：过滤所有以"<"开头以">"结尾的标签
     * @param str  
     * @return String  
     */  
    public static String filterHtml(String str) {   
        Pattern pattern = Pattern.compile("<([^>]*)>");   
        Matcher matcher = pattern.matcher(str);   
        StringBuffer sb = new StringBuffer();   
        boolean result1 = matcher.find();   
        while (result1) {   
            matcher.appendReplacement(sb, "");   
            result1 = matcher.find();   
        }   
        matcher.appendTail(sb);   
        return sb.toString();   
    }

	public static void main(String[] args) throws Exception {
		System.out.println(addSlashes("123'\"'asdasd"));
		//System.out.println(getNextMonth());
		System.out.println(daysOfTwo(parseDate("2012-05-25", "yyyy-MM-dd"), parseDate("2012-05-28", "yyyy-MM-dd")));
	}

}